package com.hezuti.common.utils;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtil {

	private static boolean RateConvert=true;
	
	 static final Log log = LogFactory.getLog(ImageUtil.class);

	private static final float QualityParam = (float) 0.98;
	
	public static int[] getImageWidthAndHeight(File file){
		 try {
			BufferedImage src = null;
			 int width,height;
			   Image i = null;
			   try {
			    src = ImageIO.read(file);
			   } catch (Exception e) {
			   }
			   if (src == null) {
			    i = Toolkit.getDefaultToolkit().createImage(file.getAbsolutePath());
			    ImageIcon ii = new ImageIcon(i);
			    width = ii.getIconWidth();
			    height = ii.getIconHeight();
			   } else {
			    width = src.getWidth();
			    height = src.getHeight();
			   }
			   return new int[]{width,height};
		 } catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}
	/*
	  * 图片裁剪，按原图比例缩放
	  * @param srcFile, 下载的原始图
	  * @param destFile,裁剪后的图片
	  */
	 public static void scaleImage(String srcFile, String destFile , double imgw , double imgh) {
	  File file1 = new File(destFile);
	  if (file1.exists()){
	   return;
	  }
	  File file = new File(srcFile);
	  if (!file.exists()) {
	   return;
	  }
	  File file2 = file1.getParentFile();
	  if (!file2.exists()){
	   file2.mkdirs();
	  }

	  int width = 0;
	  int height = 0;
	  FileOutputStream out = null;
	  try {
	   BufferedImage src = null;
	   Image i = null;
	   try {
	    src = ImageIO.read(file);
	   } catch (Exception e) {
	   }
	   if (src == null) {
	    i = Toolkit.getDefaultToolkit().createImage(srcFile);
	    ImageIcon ii = new ImageIcon(i);
	    width = ii.getIconWidth();
	    height = ii.getIconHeight();
	   } else {
	    width = src.getWidth();
	    height = src.getHeight();
	   }

	   if (width == 0 || height == 0) {
		   log.error("Source image error!");
	    return;
	   }
	   
	   double dwidth = 0;
	   double dheight = 0;
	   double w = width;
	   double h = height;
	   
	   //double propertyWidth = PropertyReader.ImageWidth;
	   //double propertyHeight = PropertyReader.ImageHeight;
	   
	   double propertyWidth = imgw;
	   double propertyHeight = imgh;
	   
	   if(RateConvert){
	    double rate = h / w;
	    if (rate >= 8.0) {
	     width = 1;
	     height = 1;
	    } else if (width > propertyWidth) {
	     dwidth = propertyWidth;
	     dheight = dwidth * rate;
	     width = (int) dwidth;
	     height = (int) dheight;
	    } else if (width <= propertyWidth && file.length() < 20000) {
	      FileUtil.cp(file, file1);
	     return;
	    }
	    if (height > propertyHeight) {
	     dheight = propertyHeight;
	     dwidth = dheight / rate;
	     width = (int) dwidth;
	     height = (int) dheight;
	    }
	    if (width <= 5 || height <= 5) {
	     width = 1;
	     height = 1;
	    }
	   }else{
	    width = (int) propertyWidth;
	    height = (int) propertyHeight;
	   }
	   
	   if (width != (int) (w + 0.1)) {
	    BufferedImage _image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	    if (src == null) {
	     _image.getGraphics().drawImage(i, 0, 0, width, height, null); // 绘制缩小后的图
	    } else {
	     _image.getGraphics().drawImage(src, 0, 0, width, height, null); // 绘制缩小后的图
	    }
	    src = _image;
	   }

	   JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(src);
	   jep.setQuality(QualityParam, false);
	   out = new FileOutputStream(file1); // 输出到文件流
	   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out, jep);
	   encoder.encode(src); // JPEG编码
	   out.close();
	  } catch (Exception exception1) {
	   try {
	    if (out != null)
	     out.close();
	   } catch (Exception ex) {
	   }
	   log.error(exception1.getMessage());
	  }
	 }

	 public static void cutImage(String srcFile, String destFile , int x1,int y1,int x2,int y2) throws IOException{
		 FileInputStream is  =   null  ;  
         ImageInputStream iis  = null  ;  
        
          try {     
              // 读取图片文件   
             is  =   new  FileInputStream(srcFile);   
               
             /*  
              * 返回包含所有当前已注册 ImageReader 的 Iterator，这些 ImageReader  
              * 声称能够解码指定格式。 参数：formatName - 包含非正式格式名称 . 
              *（例如 "jpeg" 或 "tiff"）等 。  
          */   
             Iterator < ImageReader >  it  =  ImageIO.getImageReadersByFormatName( "jpg" );    
             ImageReader reader  =  it.next();
              // 获取图片流    
             iis  =  ImageIO.createImageInputStream(is);  
                  
             /*   
              * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。 
              * 此设置意味着包含在输入源中的图像将只按顺序读取，可能允许 reader 
              *  避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。 
          */   
             reader.setInput(iis, true ) ;  
               
             /*   
              * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O  
              * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 
              * 将从其 ImageReader 实现的 getDefaultReadParam 方法中返回  
              * ImageReadParam 的实例。   
         */   
             ImageReadParam param  =  reader.getDefaultReadParam();   
                
             /*  
              * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域，通过 Rectangle 对象 
              * 的左上顶点的坐标（x，y）、宽度和高度可以定义这个区域。  
         */    
             Rectangle rect  =   new  Rectangle();
             rect.x=x1;
             rect.y=y1;
             rect.height=y2-y1;
             rect.width=x2-x1;
               
                 
              // 提供一个 BufferedImage，将其用作解码像素数据的目标。    
             param.setSourceRegion(rect);   
  
             /*  
              * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象，并将 
              * 它作为一个完整的 BufferedImage 返回。 
               */   
             BufferedImage bi  =  reader.read( 0 ,param);                  
         
              // 保存新图片    
             ImageIO.write(bi,  "jpg" ,  new  File(destFile));       
         }  finally {  
              if (is != null )  
                is.close() ;         
              if (iis != null )  
                iis.close();    
         }    
           
             
	 }

}
